/*
 * Copyright (c) Huawei Technologies Co., Ltd. 2022-2022. All rights reserved.
 */

import { formatTime } from '@ohos/hvigor';
import { Component, PathAndApiVersion, ApiVersion } from '@ohos/sdkmanager-common';
import fse from 'fs-extra';
import path from 'path';

import { ToolChainsConst } from '../../const/sdk-const.js';
import { ProjectBuildProfile } from '../../options/build/project-build-profile.js';
import { OhosLogger } from '../../utils/log/ohos-logger.js';
import { updateMetaCompileSdkVersion } from '../../utils/meta-util.js';
import { OhosSdkLoader } from '../ohos-sdk-loader.js';

import { CommonSdkInfo } from './common-sdk-info.js';
import ApiMeta = ProjectBuildProfile.ApiMeta;

const _log: OhosLogger = OhosLogger.getLogger('ohos-sdk-info');

export class OhosSdkInfo extends CommonSdkInfo {
  private readonly ohComponents: string[];
  private ohosLocalComponents: Map<PathAndApiVersion, Component> = new Map<PathAndApiVersion, Component>();

  constructor(requireComponents: string[], sdkVersion: ApiMeta, sdkDir: string) {
    super(sdkVersion, sdkDir);
    this.isOhos = true;
    this.ohComponents = requireComponents;
    this.setOhosMetaCompileSdkVersion();
  }

  setOhosMetaCompileSdkVersion() {
    updateMetaCompileSdkVersion(this.sdkVersion.version);
  }

  async setup() {
    const start: [number, number] = process.hrtime();

    // 初始化需要的所有组件key
    const pathAndApis: PathAndApiVersion[] = [];
    const fullSdkVersion: ApiVersion = new ApiVersion(this.sdkVersion.fullVersion);
    this.ohComponents.forEach((type) => pathAndApis.push(new PathAndApiVersion(type, fullSdkVersion)));

    // 拿到本地所有现存的组件并找到需要下载的组件
    this.ohosLocalComponents = await OhosSdkLoader.getInstance().getOhosSdkComponents(this.sdkVersion, this.ohComponents);

    // 初始化ohos组件
    pathAndApis.forEach((pathAndApi) => this.initComponent(this.contains(pathAndApi, this.ohosLocalComponents)!));

    this.hasRollUpPluginInJsLoader = fse.existsSync(path.resolve(this.getJsLoader(), ToolChainsConst.ROLL_UP_CONFIG_FILE));
    this.hasRollUpPluginInEtsLoader = fse.existsSync(path.resolve(this.getEtsLoader(), ToolChainsConst.ROLL_UP_CONFIG_FILE));

    const time: [number, number] = process.hrtime(start);
    _log.debug(`Sdk init in ${formatTime(time)}`);
  }

  contains(pathAndApi: PathAndApiVersion, all: Map<PathAndApiVersion, Component>) {
    for (const [key, component] of all) {
      if (key.equals(pathAndApi)) {
        return component;
      }
    }
    return undefined;
  }

  getLibimageTranscoderShared(): string {
    return '';
  }

  getHosToolchainsLibDir(): string {
    return '';
  }

  getSystemThemeSchema(): string {
    // 开源sdk需要使用开源的schema进行校验
    return this.toolchainsComponent ? this.toolchainsComponent.getSystemThemeSchema() : '';
  }
}
